package com.hippo.core.core.manager

import android.app.DownloadManager
import android.content.Context
import android.net.Uri
import android.os.Environment
import com.hippo.core.R
import com.hippo.core.core.network.HttpModule
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object FileDownloader {


    fun downloadFile(context: Context, url: String) {

        val manager: DownloadManager =
            context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        val downloadUri = Uri.parse(url)

        val request = DownloadManager.Request(downloadUri).apply {
            setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI.or(DownloadManager.Request.NETWORK_MOBILE))
            setAllowedOverRoaming(false)
            setTitle(context.getString(R.string.app_name))
            setDescription("正在下载最新版本")
            setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "hippo.apk")
            setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        }

        manager.enqueue(request);
    }





    fun download(
        url: String,
        destination: File,
        progressCallback: (Double, Long, Long) -> Unit,
        onFailed: (Throwable) -> Unit
    ) {
        val client = HttpModule.okHttpClient

        val request = Request.Builder()
            .url(url)
            .build()

        client.newCall(request).enqueue(object : okhttp3.Callback {
            override fun onFailure(call: Call, e: IOException) {
                onFailed(e)
            }

            override fun onResponse(call: Call, response: Response) {

                if (!response.isSuccessful) throw IOException("Unexpected code $response")

                val responseBody = response.body ?: throw IOException("No response body")
                val contentLength = responseBody.contentLength()

                FileOutputStream(destination).use { fos ->
                    val buffer = ByteArray(4096)
                    var totalBytesRead: Long = 0
                    var bytesRead: Int

                    while (responseBody.source().read(buffer).also { bytesRead = it } != -1) {
                        fos.write(buffer, 0, bytesRead)
                        totalBytesRead += bytesRead
                        val progress = (totalBytesRead.toDouble() / contentLength) * 100
                        progressCallback(progress,totalBytesRead, contentLength)
                    }
                }
            }
        })

    }



}